package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.model.WorkOrder;
import com.neusoft.bizcore.activiti.repository.WorkOrderRepository;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.constant.AHConstants;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.workflow.converter.JieyongConfrimSLConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.JieyongSLConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.JieyongConfrimSLDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.JieyongSLDTO;
import com.neusoft.neuiotms.dcam.workflow.model.JieyongConfrimSL;
import com.neusoft.neuiotms.dcam.workflow.model.JieyongSL;
import com.neusoft.neuiotms.dcam.workflow.repository.JieyongConfrimSLRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.JieyongSLRepository;
import com.neusoft.neuiotms.dcam.workflow.service.JieyongSLService;
import com.neusoft.neuiotms.micro.auth.AuthMicroService;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class JieyongSLServiceImpl implements JieyongSLService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private WorkOrderRepository workOrderRepository;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private JieyongSLRepository jieyongSLRepository;
    @Autowired
    private JieyongSLConverter jieyongSLConverter;
    @Autowired
    private AssetService assetService;
    @Autowired
    private JieyongConfrimSLRepository jieyongConfrimSLRepository;
    @Autowired
    private JieyongConfrimSLConverter jieyongConfrimSLConverter;
    @Autowired
    private AuthMicroService authMicroService;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;

    @Override
    @Transactional
    public JieyongSLDTO create(final JieyongSLDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_JIEYONG_SL_KEY,
                        dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());
        final List<String> orgs = user.getOrgs();
        if (orgs != null) {
            if (orgs.size() == 1) {
                dto.setOrgCode(orgs.get(0));
            } else if (orgs.size() > 1) {
                for (final String orgItem : orgs) {
                    if (orgItem.length() == 2) {
                        dto.setOrgCode(orgItem);
                        break;
                    }
                }
            }
            dto.setOrgName(this.authMicroService.orgInfoByCode(dto.getOrgCode()).getData().get("name").toString());
        }

        // 查询当前workOrderNum和TaskId下是否存在记录
        final JieyongSL oldModel = this.jieyongSLRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        JieyongSL model = this.jieyongSLConverter.toModel(dto);
        model = this.jieyongSLRepository.save(model);

        // 确认节点审批人
        final List<String> users = new ArrayList<>();
        final Map<String, Object> search = new HashMap<>();
        search.put("s_orgCode", dto.getOrgCode());
        search.put("s_roleCode", AHConstants.ROLE_SL_DEPT_ASSET_ADMIN);
        final ResultListDTO<Map<String, Object>> userList = this.authMicroService.userIndex(search);
        userList.getData().stream().map(l -> l.get("username").toString()).filter(s -> null != s)
                .forEach(users::add);
        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_DISPATCHUSERLIST,
                users);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        final JieyongSLDTO result = this.jieyongSLConverter.toDTO(model);

        return result;
    }

    @Override
    public JieyongSLDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        JieyongSL model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.jieyongSLRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new JieyongSLDTO();
                    } else {
                        model = this.jieyongSLRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model = this.jieyongSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.jieyongSLConverter.toDTO(model);
    }

    @Override
    public void reject(final String workOrderNum) {

        // 解锁以前的资产信息
        final List<JieyongConfrimSL> all = this.jieyongConfrimSLRepository.findByWorkOrderNum(workOrderNum);
        if (null != all) {
            final List<Asset> list = all.stream().map(it -> {
                final Asset at = this.assetRepository.findByCode(it.getCode());
                at.setStatus(it.getStatus());
                at.setLocked(false);
                return at;
            }).collect(Collectors.toList());

            if (!all.isEmpty()) {
                this.assetRepository.saveAll(list);
            }
        }

    }

    @Override
    public List<JieyongConfrimSLDTO> confrimCreate(final List<JieyongConfrimSLDTO> dto, final UserBean user) {

        final List<JieyongConfrimSL> models = this.jieyongConfrimSLConverter.toListModel(dto);
        this.jieyongConfrimSLRepository.saveAll(models);

        // 枷锁资产
        this.assetService.updateLocked(dto.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        // 完成当前节点
        this.processInstanceService.complete(dto.get(0).getWorkOrderNum(), dto.get(0).getTaskId(), user);

        //        this.jieyongCompleteUpdate(dto, dto.get(0).getWorkOrderNum());

        return this.jieyongConfrimSLConverter.toListDTO(models);

    }

    @Override
    public JieyongSLDTO confrimDetail(final String workOrderNum, final String taskId, final UserBean user) {
        JieyongSLDTO dto = new JieyongSLDTO();
        // 获取条件
        final JieyongSL Jieyong =
                this.jieyongSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        if (Jieyong != null) {
            dto = this.jieyongSLConverter.toDTO(Jieyong);
        }

        List<JieyongConfrimSL> model = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.jieyongConfrimSLRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                dto.setJieyong(this.jieyongConfrimSLConverter.toListDTO(model));
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return dto;
    }

    @Override
    public List<JieyongConfrimSLDTO> distributeCreate(final List<JieyongConfrimSLDTO> dto, final UserBean user) {

        final List<JieyongConfrimSL> models = dto.stream().map(l -> {
            final JieyongConfrimSL model = this.jieyongConfrimSLRepository.getOne(l.getId());
            model.setJieyongUserCode(l.getJieyongUserCode());
            model.setJieyongUserName(l.getJieyongUserName());
            model.setJieyongLocation(l.getJieyongLocation());
            model.setJieyongLocationName(l.getJieyongLocationName());
            return model;
        }).collect(Collectors.toList());

        this.jieyongConfrimSLRepository.saveAll(models);

        this.processInstanceService.setGlobalVariable(dto.get(0).getTaskId(),
                "passFlag", true);

        this.processInstanceService.complete(dto.get(0).getWorkOrderNum(), dto.get(0).getTaskId(), user);

        this.jieyongCompleteUpdate(dto, dto.get(0).getWorkOrderNum());
        return this.jieyongConfrimSLConverter.toListDTO(models);
    }

    private void jieyongCompleteUpdate(final List<JieyongConfrimSLDTO> dto, final String workOrderNum) {

        final JieyongSL jieyong =
                this.jieyongSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);

        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();

        final List<Asset> assets = dto.stream().map(l -> {
            final Asset model = this.assetRepository.findByCode(l.getCode());
            model.setManagementUserCode(l.getJieyongUserCode());
            model.setManagementUserName(l.getJieyongUserName());
            model.setManagementOrgCode(jieyong.getOrgCode());
            model.setManagementOrgName(jieyong.getOrgName());
            model.setLocation(l.getJieyongLocation());
            model.setLocationName(l.getJieyongLocationName());
            model.setStatus(DCAMConsts.ASSET_STATUS_BORROW);
            model.setLocked(false);
            // 生命周期
            lifeList.add(AssetLifeCycleDTO.builder().code(model.getCode())
                    .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_JIEYONG)
                    .content(model.getName() + "被借用").workNum(workOrderNum).build());
            return model;
        }).collect(Collectors.toList());

        if ((assets != null) && (assets.size() > 0)) {
            this.assetRepository.saveAll(assets);
        }

        if (lifeList.size() > 0) {
            this.assetLifeCycleService.batchCreate(lifeList);
        }

    }

    @Override
    public JieyongSLDTO distributeDetail(final String workOrderNum, final String taskId,
            final UserBean user) {

        final JieyongSL Jieyong =
                this.jieyongSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        final JieyongSLDTO dto = this.jieyongSLConverter.toDTO(Jieyong);

        List<JieyongConfrimSL> model = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.jieyongConfrimSLRepository.findByWorkOrderNumOrderByIdDesc(workOrderNum);
                final String lastTaskId = model.get(0).getTaskId();
                model = model.stream().filter(it -> lastTaskId.equals(it.getTaskId())).collect(Collectors.toList());
                dto.setJieyong(this.jieyongConfrimSLConverter.toListDTO(model));
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return dto;
    }

    @Override
    public List<JieyongSLDTO> search(final Searchable searchable) {
        final List<JieyongSL> models = this.jieyongSLRepository.search(searchable);
        return this.jieyongSLConverter.toListDTO(models);
    }

    @Override
    public Page<JieyongSLDTO> search(final Pageable pageable, final Searchable searchable) {
        final Searchable params = new Searchable();
        params.put("type", "JieyongSL");
        params.put("status", "finish");
        final List<WorkOrder> finishedWorkorderList = this.workOrderRepository.search(params);
        final List<String> finishedWorkorderWorkNumList =
                finishedWorkorderList.stream().map(it -> it.getWorkOrderNum()).collect(Collectors.toList());

        searchable.put("workOrderNumIn", finishedWorkorderWorkNumList);
        final Page<JieyongSL> models = this.jieyongSLRepository.search(pageable, searchable);
        final Page<JieyongSLDTO> dtos = this.jieyongSLConverter.toPageDTO(models);
        return dtos;
    }

    @Override
    public JieyongSLDTO detail(final Long id) {
        final JieyongSL model = this.jieyongSLRepository.findById(id).orElse(null);
        if (null != model) {
            final JieyongSLDTO dto = this.jieyongSLConverter.toDTO(model);

            List<JieyongConfrimSL> confirmedAssetList = new ArrayList<>();
            try {
                if (StringUtils.isNotBlank(model.getWorkOrderNum())) {
                    confirmedAssetList = this.jieyongConfrimSLRepository.findByWorkOrderNum(model.getWorkOrderNum());
                    dto.setJieyong(this.jieyongConfrimSLConverter.toListDTO(confirmedAssetList));
                }
            } catch (final EntityNotFoundException e) {
                JieyongSLServiceImpl.log.error("", e);
            }

            final List<JieyongConfrimSLDTO> detailItems = dto.getJieyong();
            final List<String> assetCodeList =
                    detailItems.stream().map(it -> it.getCode()).collect(Collectors.toList());
            final Searchable params = new Searchable();
            params.put("codes", assetCodeList);
            final List<AssetDTO> assetList = this.assetService.index(params);
            dto.setAssetStandingBook(assetList);

            //            for (final JieyongConfrimSLDTO jieyongItemSL : detailItems) {
            //                final Asset asset = this.assetRepository.findByCode(jieyongItemSL.getCode());
            //                jieyongItemSL.setMeasureUnit(asset.getMeasureUnit());
            //                jieyongItemSL.setBrand(asset.getBrand());
            //            }
            //            dto.setJieyong(detailItems);
            return dto;
        }
        return null;
    }

}
